import Vue from 'vue'
import { getToken } from '@/utils/local'
import VueRouter from 'vue-router'
import Layout from '@/views/Layout'
const Detail = () => import('@/views/Detail')
const Register = () => import('@/views/Register')
const Login = () => import('@/views/Login')
const Article = () => import('@/views/Article')
const Collect = () => import('@/views/Collect')
const Like = () => import('@/views/Like')
const My = () => import('@/views/My.vue')

// 将
// import UserDetails from './views/UserDetails.vue'
// 替换成
// const UserDetails = () => import('./views/UserDetails.vue')

// import Login from '@/views/Login.vue'
Vue.use(VueRouter)

const routes = [
  { path: '/login', component: Login },
  { path: '/register', component: Register },
  { path: '/detail/:id', component: Detail },
  {
    path: '/',
    component: Layout,
    redirect: '/article',
    children: [
      { path: '/article', component: Article },
      { path: '/collect', component: Collect },
      { path: '/like', component: Like },
      { path: '/my', component: My }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 路由守卫 前置守卫 beforeEach
// 应用场景  登录拦截   权限拦截  等
// 1. to 要去哪(route)
// 2. from 从哪来
// 3. next() 跳转方法  next() 直接方向  next(false) 跳转失败  next(路径) 跳转到指定页面

// 判断有没有token  有token才能跳到首页...  没token能去的页面 登录  注册
// 利用白名单 来操作不需要token就能去的页面
const whiteList = ['/login', '/register']
router.beforeEach((to, from, next) => {
  const token = getToken()
  console.log(to, from)
  console.log(token)
  if (token) {
    next()
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
